/*
 * ClienteHTTP.java
 *
 * Created on 7 de marzo de 2006, 09:03 AM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package ig.formato.util;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 *
 * @author jsanchez
 */
public class ClienteHTTP {
    private Socket socket = null;
    private InputStream is = null;
    private OutputStream os = null;
    private BufferedReader entrada =null;
    private DataInputStream dis =null;
    private PrintStream ps =null;
    private int secuencia=0;
    DataOutputStream brOut =null;
    DataInputStream br =null;
    
    private String host=null;
    private Integer pueto=null;
            
    /** Creates a new instance of ClienteHTTP */
    public ClienteHTTP(String host,Integer pueto) {
        this.host=host;
        this.pueto=pueto;        
    }
    
    private boolean conectar() throws Exception{
        try {
            socket = new Socket(host,pueto);
            is = socket.getInputStream();
            os = socket.getOutputStream();
            entrada = new BufferedReader( new InputStreamReader( socket.getInputStream() ) );
           
            File erroe= new File("tmp/error.html");
            File dir= new File("tmp");
            if(!dir.exists()){
                dir.mkdir();
            }
            if(erroe.exists()){
                try {
                    erroe.delete();
                } catch (Exception e) {}
            }
            brOut =new DataOutputStream(new BufferedOutputStream(new FileOutputStream("tmp/error.html")));
        } catch (UnknownHostException ex) {
        	ex.printStackTrace();
            throw new Exception("Valores Invalidos de conexion:\nhost=["+host+"]  puerto:["+pueto+"]");
        } catch (IOException ex) {
        	ex.printStackTrace();
            throw new Exception("Valores Invalidos de conexion:\nhost=["+host+"]  puerto:["+pueto+"]");
        }
        dis = new DataInputStream(is);
        ps = new PrintStream(os);        
        return true;
    }
    
    StringBuffer HEADER= new StringBuffer("");    
    public int getSecuencia() {
        return secuencia;
    }
    
    public StringBuffer getHEDER() {
        return HEADER;
    }
    StringBuffer HTML=null;
    String END=null;
    public String getHTML(String pathHtml)throws Exception{
        
        if(conectar()){
            HEADER=new StringBuffer("");
            HTML= new StringBuffer("");
            try {
                if(pathHtml.toLowerCase().startsWith("http://")){
                    pathHtml=pathHtml.substring("http://".length());
                    int del=pathHtml.split("/")[0].length()+1;
                    pathHtml=pathHtml.substring(del);
                }
                System.out.println("pathHtml:"+ pathHtml);
                ps.println("GET /" +pathHtml+" HTTP/1.0");
                ps.println("User-Agent: Java");
                ps.println("Content-type: application/x-www-form-urlencoded");
                ps.println("Content-length: " + 0);
                ps.println();
                ps.flush();
                
                String linea = null;
                
                while( (linea = entrada.readLine()) != null ) {
                    HEADER.append(linea+"\n");
                    if(linea .equals("")) break;
                }
//              System.out.println("----- END HEADER -----");
                
                boolean body=false;
                while( (linea = entrada.readLine()) != null ) {
                    if(HTML.length()>0)
                        HTML.append("\n");
                    if(linea!=null && !linea.trim().equals("")){
                        HTML.append(linea.trim().replaceAll("#"," ").replaceAll("_&_",""));
                    }
                }
                if(HTML.toString().contains("<html>")){
                    brOut.writeBytes(HTML.toString());
                    brOut.flush();
                    brOut.close();
                }
            }catch (Exception ex) {
                throw ex;
            }finally {
                try {
                    is.close();
                    dis.close();
                    os.close();
                    ps.close();
                    socket.close();
                } catch (Exception e) {}
                if(HTML.toString().trim().equals("")){
                    throw new Exception("URL Invalida:\nprotocolo=http\nhost="+host+"\npuerto="+pueto+"\npeticion="+pathHtml);
                }                    
                return HTML.toString()/*.replaceAll("#"," ")*/;
            }
        }
        return "";
    }
    private void guardar(String path){
//        _HTML_.append("<html>");
//        _HTML_.append("<head>");
//        _HTML_.append("<title>OutPut_Server</title>");
//        _HTML_.append("  </head>");
//        _HTML_.append("  <body>");
        BufferedWriter br =null;
        FileOutputStream fileOutRunBat=null;
        try {
            //System.out.println("-->"+path);
            fileOutRunBat = new FileOutputStream(path);
            br = new BufferedWriter(new OutputStreamWriter(fileOutRunBat));
//            _HTML_.append(html);
//            _HTML_.append("  </body>");
//            _HTML_.append("</html>");
            br.write(HEADER.toString());
            br.write(HTML.toString());
            br.flush();
            br.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    public static void main(String arg[]) throws Exception{
        ClienteHTTP cliente= new ClienteHTTP("localhost",8080);
        System.out.println(cliente.getHTML("" +                
                "ServicioReportes/GenerarReporte.pdf?formato=txt" +                
                "&reporte=ejemplo"+
                "&ds=METRICADW" +
                "&parametros=ID_EMPRESA=1=java.lang.Integer"));
                
        /*
        System.out.println(cliente.getHTML("" +
                "ServicioReportes/GenerarReporte.txt?operacion=generarreporte" +
                "&formato=txt" +
                "&reporte=ejemplo" +
                "&FECHA_CORTE=2006-10-02 00:00:00.0" +
                "&FECHA_CORTE_TIPO=java.sql.Timestamp%3Dyyyy-MM-dd+hh%3Amm%3Ass.0" +
                "&ID_ENTIDAD=1" +
                "&ID_ENTIDAD_TIPO=java.lang.Integer" +
                "&parametros=ID_ENTIDAD%3BFECHA_CORTE" +
                "&ds=FORMATO" +
                "&ds=METRICADW"));*/
        /*System.out.println(cliente.getHTML("" +
                "ServicioReportes/GenerarReporte.pdf?formato=txt" +
                "&reporte=ejemplo" +
                "&ds=METRICADW" +
                "&parametros=ID_EMPRESA=1=java.lang.Integer" +
                ";FECHA=2008-02-02 00:00:00.0=java.sql.Timestamp=yyyy-mm-dd" +
                ";ID_ENTIDAD=000025=java.lang.String"));*/
    }
}

























